package cn.rayland.rayland3d.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import cn.rayland.rayland3d.R;
import cn.rayland.rayland3d.app.App;
import utils.EasySharePreference;
import utils.WebSocketPusher;

/**
 * Created by gw on 2016/3/28.
 */
public class StateActivity extends AppCompatActivity implements View.OnClickListener {
    private Handler handler = new Handler();
    private Runnable runnable;
    private Button addPrint;
    private Button pausePrint;
    private Button resumePrint;
    private Button cancelPrint;
    private TextView printState;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_state);
        initView();
        startGetPrintState();
    }

    private void initView() {
        printState = (TextView) findViewById(R.id.printer_state);
        addPrint = (Button) findViewById(R.id.add_print);
        pausePrint = (Button) findViewById(R.id.pause_print);
        resumePrint = (Button) findViewById(R.id.resume_print);
        cancelPrint = (Button) findViewById(R.id.stop_print);
        addPrint.setOnClickListener(this);
        pausePrint.setOnClickListener(this);
        resumePrint.setOnClickListener(this);
        cancelPrint.setOnClickListener(this);
    }

    //定时获取打印机状态
    private void startGetPrintState() {
        runnable = new Runnable(){
            @Override
            public void run() {
                try {
                    printState.setText(App.machineManager.getMachineState().toString());
                }catch (Exception e){}
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(runnable);
        super.onDestroy();

    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.add_print:
                //调整打印速度， 初始速度的%300， 范围0~500
                App.machineManager.sendCommand("M221 S300");
                //调整打印温度， 250℃(M104边打印边升温， M109先升温再打印)
                App.machineManager.sendCommand("M104 S240");
                break;
            case R.id.pause_print:
                //暂停打印
                App.machineManager.pause();
                break;
            case R.id.resume_print:
                //恢复打印
                App.machineManager.resume();
                break;
            case R.id.stop_print:
                //取消打印
                App.machineManager.cancel(true);
                if (EasySharePreference.getPrefInstance(getApplicationContext()).getBoolean("ifpush", false)){
                    WebSocketPusher.stopPush();
                }
                finish();
                break;
        }
    }
}
